package cn.jzq.kotoba.modules.sharding.controller;

import cn.hutool.core.date.DateUtil;
import cn.jzq.kotoba.common.consts.CommonConst;
import cn.jzq.kotoba.common.util.R;
import cn.jzq.kotoba.modules.sharding.model.entity.Student;
import cn.jzq.kotoba.modules.sharding.service.StudentService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 读写分离测试
 * spring团队推荐构造器注入, 因为它使应用程序组件能够实现为不可变对象，并确保所需的依赖项不为空
 * 依赖不可变 components as immutable objects ，即注入对象为final
 * 依赖不可为空required dependencies are not null，省去对注入参数的检查。当要实例化FooController的时候，由于只有带参数的构造函数，spring注入时需要传入所需的参数，所以有两种情况：1) 有该类型的参数传入 => ok; 2) 无该类型参数传入，报错
 * 提升了代码的可复用性：非IOC容器环境可使用new实例化该类的对象。
 * 避免循环依赖：如果使用构造器注入，在spring项目启动的时候，就会抛出：BeanCurrentlyInCreationException：Requested bean is currently in creation: Is there an unresolvable circular reference？从而提醒你避免循环依赖，如果是field注入的话，启动的时候不会报错，在使用那个bean的时候才会报错。
 *
 *
 * @author jzq
 * @date 2018-09-16
 */
@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;

//    @Autowired
//    public StudentController(StudentService studentService) {
//        this.studentService = studentService;
//    }

    @GetMapping("")
    @ApiOperation(value = "获取所有的student")
    public R<List<Student>> listStudent() {
//        return new R<>(studentService.list(null));
        return new R<>(studentService.injectionTest());
    }

    @GetMapping("/date")
    public R getDate() {
        return R.ok(DateUtil.now());
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "根据id获取student")
    @ApiImplicitParam(name = "id", value = "student.id", required = true, dataType = "Long")
    public R<Student> getStudent(@PathVariable("id") Long id) {
        return new R<>(studentService.getById(id));
    }

    @PostMapping("")
    @ApiOperation(value = "新增student", notes = "根据条件新增student")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "姓名", required = true)
    })
    public R<Boolean> student(@RequestBody Student student) {
        student.setDelFlag(CommonConst.STATUS_NORMAL);
        student.setCreateTime(DateUtil.date());
        return new R<>(studentService.save(student));
    }
}
